#!/bin/sh

#
# Test that signing firmware does the expected thing using
# raw (non base64-encoded) keys. This ensures that fwup users
# using keys created by older versions of the software still
# work.
#

. "$(cd "$(dirname "$0")" && pwd)/common.sh"

cat >$CONFIG <<EOF
file-resource TEST {
	host-path = "${TESTFILE_1K}"
}

task complete {
	on-resource TEST { raw_write(0) }
}
EOF

cat >$EXPECTED_META_CONF <<EOF
file-resource "TEST" {
  length=1024
  blake2b-256="b25c2dfe31707f5572d9a3670d0dcfe5d59ccb010e6aba3b81aad133eb5e378b"
}
task "complete" {
  on-resource "TEST" {
    funlist = {"2", "raw_write", "0"}
  }
}
EOF

# Create new keys and their raw (old style) versions and
# unpadded base64 versions.
cd $WORK
$FWUP_CREATE -g
base64_decode < fwup-key.priv > fwup-key.priv.raw
base64_decode < fwup-key.pub > fwup-key.pub.raw
dd if=fwup-key.pub of=fwup-key.pub.unpadded bs=1 count=43
dd if=fwup-key.priv of=fwup-key.priv.unpadded bs=1 count=86
cd -

# Sign the firmware
$FWUP_CREATE --private-key-file $WORK/fwup-key.priv.raw -c -f $CONFIG -o $FWFILE

# Check that the zip file was created as expected
check_meta_conf

# Check that applying the firmware without checking signatures works
$FWUP_APPLY -q -a -d $IMGFILE -i $FWFILE -t complete

# Check that verifying the firmware without checking signatures works
$FWUP_VERIFY -V -i $FWFILE

# Check that applying the firmware with checking signatures works
$FWUP_APPLY -q -p $WORK/fwup-key.pub.raw -a -d $IMGFILE -i $FWFILE -t complete
$FWUP_APPLY -q --public-key-file $WORK/fwup-key.pub.raw -a -d $IMGFILE -i $FWFILE -t complete

# Check that using the base64-encoded key still works as well.
$FWUP_APPLY -q -p $WORK/fwup-key.pub -a -d $IMGFILE -i $FWFILE -t complete

# While we're at it, check that an unpadded key works
$FWUP_APPLY -q -p $WORK/fwup-key.pub.unpadded -a -d $IMGFILE -i $FWFILE -t complete

# Check that verifying the firmware with checking signatures works
$FWUP_VERIFY -V -p $WORK/fwup-key.pub.raw -i $FWFILE

# Check that using the base64-encoded key still works as well.
$FWUP_VERIFY -V -p $WORK/fwup-key.pub -i $FWFILE

$FWUP_VERIFY -V -p $WORK/fwup-key.pub.unpadded -i $FWFILE
